package dao.impl;

import dao.UserDao;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import pojo.User;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class UserDaoImpl implements UserDao {

    @Override
    public List<User> findAll() {
      // 引入mybatis配置文件
        SqlSession sqlSession = null;
        String resourse = "mybatis-config.xml";
        //加载配置文件
    try{
        InputStream inputStream = Resources.getResourceAsStream(resourse);
        //创建会话工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 创建会话
        sqlSession = sqlSessionFactory.openSession();
        // 执行查询
        List<User> users = sqlSession.getMapper(UserDao.class).findAll();
        //返回查询结果
        return users;
    } catch (IOException e) {
            throw new RuntimeException(e);
       }finally {
        sqlSession.close();
    }
    }
}
